<?php

namespace app\controller;


use app\model\HighShop;
use app\model\UserOrder;
use app\model\UserWatchAdLog;
use app\service\HighShopService;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

//至臻商店控制器
class HighShopController extends Base
{

    /**
     * 获取至臻店信息
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function list(): Response
    {
        $high_shop_list = (new HighShop())->select();
        foreach ($high_shop_list as &$item) {
            $this->handleModelData($item);
        }

        //查询本周的观看记录
        $ad_count = (new UserWatchAdLog())->where('user_id', $this->user_id)->order('created_at desc')->whereTime('created_at', 'week')->count();

        foreach ($high_shop_list as &$high_shop) {
            //用户已经领取的奖励
            $user_order_count = (new UserOrder())->where('user_id', $this->user_id)->where('shop_type', SHOP_TYPE['至臻商店'])->where('shop_id', $high_shop->id)->whereTime('created_at', 'week')->count();
            $high_shop->is_get = 0;//有没有获取
            if ($user_order_count) {
                $high_shop->is_get = 1;
            }
            $high_shop->is_unlock = 0;//有没有解锁
            if ($ad_count >= $high_shop->count) {
                $high_shop->is_unlock = 1;//有没有解锁
            }
        }

        $data = [
            'list' => $high_shop_list->toArray(),
            'day_max' => HIGH_SHOP_CONFIG['每日最大购买次数'],//每日最大购买次数
            'interval' => HIGH_SHOP_CONFIG['每次间隔时间'],//每次间隔时间
            'total' => $ad_count//当前累计观看次数
        ];


        return $this->success('ok', $data);
    }


    //观看广告
    public function watch(): Response
    {
        // 启动事务
        Db::startTrans();

        try {
            $res = (new HighShopService())->watch($this->user_id);

            if ($res['code']) {
                Db::commit();
            } else {
                Db::rollback();
            }
            return $this->json($res);

        } catch (\Exception $e) {
            Db::rollBack();
            return $this->fail("服务器异常" . $e->getLine());
        }

    }

    //领取奖励
    public function reward(): Response
    {

        $high_shop_id = $this->request->post('high_shop_id');
        if (empty($high_shop_id)) {
            return $this->fail('参数错误');
        }
        // 启动事务
        Db::startTrans();

        try {
            $res = (new HighShopService())->reward($this->user_id, $high_shop_id);

            if ($res['code']) {
                Db::commit();
            } else {
                Db::rollback();
            }
            return $this->json($res);

        } catch (\Exception $e) {
            Db::rollBack();
            return $this->fail("服务器异常" . $e->getLine());
        }


    }


}